package com.commerce.user.controller;

import com.commerce.common.entity.User;
import com.commerce.common.utils.JwtUtil;
import com.commerce.common.utils.Result;
import com.commerce.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户登录
     */
    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<Map<String, Object>> login(@RequestBody(required = true) Map<String, String> loginForm) {
        try {
            log.info("收到登录请求: {}", loginForm);
            
            // 验证请求数据
            if (loginForm == null || !loginForm.containsKey("username") || !loginForm.containsKey("password")) {
                return Result.error("请求数据格式错误，需要提供username和password");
            }
            
            String username = loginForm.get("username");
            String password = loginForm.get("password");
            
            if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
                return Result.error("用户名和密码不能为空");
            }
            
            // 查询用户
            User user = userService.getUserByUsername(username.trim());
            if (user == null) {
                return Result.error("用户名不存在");
            }
            
            // 校验密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                return Result.error("密码错误");
            }
            
            // 更新登录时间
            user.setLastLoginTime(LocalDateTime.now());
            userService.updateById(user);
            
            // 生成JWT token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            claims.put("username", user.getUsername());
            String token = jwtUtil.generateToken(claims);
            
            // 清除敏感信息
            user.setPassword(null);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", user);
            
            log.info("用户 {} 登录成功", username);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<Map<String, Object>> register(@RequestBody Map<String, String> registerForm) {
        try {
            log.info("收到注册请求");
            
            // 验证请求数据
            if (registerForm == null || !registerForm.containsKey("username") || 
                !registerForm.containsKey("password") || !registerForm.containsKey("email")) {
                return Result.error("请求数据格式错误，需要提供username、password和email");
            }
            
            String username = registerForm.get("username");
            String password = registerForm.get("password");
            String email = registerForm.get("email");
            String phone = registerForm.get("phone");
            
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            // 创建用户对象
            User user = new User();
            user.setUsername(username.trim());
            user.setEmail(email);
            user.setPhone(phone);
            
            // 设置默认值
            if (registerForm.containsKey("realName")) {
                user.setRealName(registerForm.get("realName"));
            }
            
            // 注册用户
            User registeredUser = userService.register(user, password);
            
            // 生成JWT token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", registeredUser.getId());
            claims.put("username", registeredUser.getUsername());
            String token = jwtUtil.generateToken(claims);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", registeredUser);
            
            log.info("用户 {} 注册成功", username);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error("注册失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户权限
     */
    @GetMapping("/permissions")
    public Result<List<Long>> getPermissions(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "未提供有效的token");
            }
            
            token = token.substring(7);
            
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                return Result.error(401, "token已过期或无效");
            }
            
            // 获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error(401, "无效的token");
            }
            
            // 获取用户权限
            List<Long> permissions = userService.getUserPermissions(userId);
            return Result.success(permissions);
            
        } catch (Exception e) {
            log.error("获取权限失败", e);
            return Result.error(500, "获取权限失败: " + e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 这里可以添加token黑名单等登出逻辑
            }
            return Result.success("退出成功");
        } catch (Exception e) {
            log.error("退出失败", e);
            return Result.error("退出失败：" + e.getMessage());
        }
    }
} 